//
//  CompanyMainDetailsVController.m
//  ShangPiBao
//
//  Created by chirui on 2017/10/19.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "CompanyMainDetailsVController.h"
#import "CompanyGoodsViewController.h"
#import "FMDB.h"
#import "DBModel.h"
#import "DBManager.h"


@interface CompanyMainDetailsVController ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger buttonCurryIndex;
    UITableView * _tableView;
    UIView * lineView;
    CompanyGoodsViewController * _companyGoods;
    NSDictionary * companyDic;
    UIImageView * companyImage;
    UILabel * companyName;
    
    FMDatabase * dataBase;
    BOOL _isCollected;
    
}
@end

@implementation CompanyMainDetailsVController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor =[UIColor groupTableViewBackgroundColor];
    
    TitleView(@"公司详情");
    [self ceratTopView];
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_return" target:self action:@selector(backClick)];
    [self getMyCenterMessageForRequest];
    
    _isCollected = [[DBManager sharedManager] isDataExistByAppId:self.companyId];
    
    if (_isCollected) {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon :@"icon_nav_collect_click" target:self action:@selector(okCollectClick:)];
    }else{
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon :@"icon_nav_collect" target:self action:@selector(collectClick:)];
    }
    [self lookNumberRequesr];
    
}

-(void)okCollectClick:(UIButton *)btn{
    
    SHuiMBhudTextTimeStr(@"已收藏!");
    return;

}

-(void)collectClick:(UIButton *)collect{
    
  
    DBModel *model = [[DBModel alloc] init];
    model.appId = companyDic[@"uid"];
    model.name = companyDic[@"ucn"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *str = [formatter stringFromDate:[NSDate date]];

    model.time = str;
    
    BOOL addSuc = [[DBManager sharedManager] addDataFromModel:model];
    
    if (addSuc) {
        
        SHuiMBhudTextTimeStr(@"收藏成功!");
        
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon :@"icon_nav_collect_click" target:self action:@selector(okCollectClick:)];
        
        return;
       
    }else {
        NSLog(@"加入收藏失败！");
    }

}

-(void)backClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)ceratTopView {
    
    buttonCurryIndex = 1;
    UIView * bgView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
    bgView.backgroundColor =[UIColor blackColor];
    [self.view addSubview:bgView];
    
    companyImage =[[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 80, 80)];
    companyImage.backgroundColor =[UIColor whiteColor];
    companyImage.layer.cornerRadius = 6.f;
    companyImage.layer.masksToBounds = YES;
    [bgView addSubview:companyImage];
    
    companyName =[[UILabel alloc]initWithFrame:CGRectMake(110, 50, WIDTH -120, 20)];
    companyName.textColor = [UIColor whiteColor];
    companyName.font =[UIFont boldSystemFontOfSize:15];
    companyName.text  = self.companyNameStr;
    companyName.numberOfLines =2;
    [companyName sizeToFit];
    [bgView addSubview:companyName];
    UIView * titleView =[[UIView alloc]initWithFrame:CGRectMake(0, 120,  self.view.frame.size.width, 50)];
    titleView.backgroundColor = GoldTextColor;
    [self.view addSubview:titleView];
    
    NSArray * titleArray = @[@"经营范围",@"产品中心",@"联系我们"];
    for (int i = 0; i<3; i++) {
        
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(WIDTH/3 * i, 0, WIDTH/3, 50);
        btn.tag = 1000+i;
        [btn setTitle:titleArray[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.backgroundColor =[UIColor clearColor];
        if (i==buttonCurryIndex) {
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            btn.backgroundColor = RGB(0x8b6939);
            _companyGoods =[[CompanyGoodsViewController alloc]init];
            _companyGoods.companyId = self.companyId;
            _companyGoods.view.frame = CGRectMake(0,170 , WIDTH, HEIGHT - 235);
            [self addChildViewController:_companyGoods];
            [self.view addSubview:_companyGoods.view];
            
//            lineView =[[UIView alloc]initWithFrame:CGRectMake(WIDTH/3*buttonCurryIndex, 48, WIDTH/3, 3)];
//            lineView.backgroundColor = [UIColor blackColor];
//            [titleView addSubview:lineView];
        }
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:btn];
    }
}

-(void)btnClick:(UIButton *)btn{
    NSInteger i = btn.tag - 1000;
    if (buttonCurryIndex==i) {
        return;
    }
    UIButton * button = (id)[self.view viewWithTag:buttonCurryIndex+1000];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.backgroundColor =RGB(0x8b6939);
    button.backgroundColor =[UIColor clearColor];
    lineView.center= CGPointMake(btn.center.x, 49);
    buttonCurryIndex = i;
    NSLog(@"btttonCurryIndex == %ld",buttonCurryIndex);
    if (buttonCurryIndex ==0) {
        [_companyGoods.view removeFromSuperview];
        if (_tableView) {
            [_tableView removeFromSuperview];
        }
        [self creatTableView];
        
    }
    if (buttonCurryIndex ==1) {
        [_tableView  removeFromSuperview];
        _companyGoods =[[CompanyGoodsViewController alloc]init];
        _companyGoods.companyId = self.companyId;
        _companyGoods.view.frame = CGRectMake(0,170 , WIDTH, HEIGHT - 235);
        [self addChildViewController:_companyGoods];
        [self.view addSubview:_companyGoods.view];
    }
    if (buttonCurryIndex ==2) {
        if (_tableView) {
            [_tableView removeFromSuperview];
        }
        [self creatTableView];
      
       
        [_companyGoods.view removeFromSuperview];
    }
}

-(void)creatTableView{
    _tableView  =[[UITableView alloc]initWithFrame:CGRectMake(0, 170, WIDTH, HEIGHT -236) style:UITableViewStyleGrouped];
    _tableView.delegate =self;
    _tableView.dataSource =self;
    _tableView.backgroundColor =[UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:_tableView];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (buttonCurryIndex ==0) {
        return 1;
    }else {
        return 5;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (buttonCurryIndex ==0) {
        UILabel * label =[[UILabel alloc]initWithFrame:CGRectMake(10, 20, WIDTH - 20, 20)];
        label.font = [UIFont systemFontOfSize:15];
        if (companyDic) {
            label.text = companyDic[@"uor"];
        }
        label.numberOfLines = 0;
        [label sizeToFit];
        return CGRectGetMaxY(label.frame)+20;
    }else {
        return 50;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray * array = @[@"地址",@"电话/传真",@"手机",@"联系人",@"网址"];
    static NSString * str = @"cellid";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell==nil) {
        
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }else {
        while ([cell.contentView.subviews lastObject]!=nil) {
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    

    if (buttonCurryIndex==0) {
        UILabel * label =[[UILabel alloc]initWithFrame:CGRectMake(10, 20, WIDTH - 20, 20)];
        label.font = [UIFont systemFontOfSize:15];
        
        if (companyDic) {
            label.text = companyDic[@"uor"];
        }
        
        label.numberOfLines = 0;
        [label sizeToFit];
        [cell.contentView addSubview:label];
    }else{
        UILabel * title = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, 100, 20)];
        title.font = [UIFont systemFontOfSize:15];
        title.text = array[indexPath.row];
        [cell.contentView addSubview:title];
        UILabel * details = [[UILabel alloc]initWithFrame:CGRectMake(120, 15, WIDTH - 120, 20)];
        details.font = [UIFont systemFontOfSize:15];
        details.textColor =[UIColor grayColor];
        if (companyDic) {
            
           NSArray *    detailsArray = [companyDic[@"uci"] componentsSeparatedByString:@"|"];
             details.text = detailsArray[indexPath.row];
        }
        if (indexPath.row==2||indexPath.row==1) {
            
            UIButton * phoneBtn =[UIButton buttonWithType:UIButtonTypeCustom];
            phoneBtn.frame = CGRectMake(WIDTH- 40, 15/2, 30, 30);
            [phoneBtn setBackgroundImage:ImageName(@"icon_new_phone") forState:UIControlStateNormal];
            phoneBtn.tag = 100+indexPath.row;
            [phoneBtn addTarget:self action:@selector(phoneBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:phoneBtn];
            
        }
       
        UIView * line_0neView =[[UIView alloc]initWithFrame:CGRectMake(10, 44.5, WIDTH - 20, 0.5)];
        line_0neView.backgroundColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:line_0neView];
        [cell.contentView addSubview:details];
    }
    return cell;
}

-(void)phoneBtnClick:(UIButton *)btn{
    
    NSString * phoneStr;
    if (companyDic) {
        
        NSArray *    detailsArray = [companyDic[@"uci"] componentsSeparatedByString:@"|"];
        phoneStr = detailsArray[btn.tag - 100];
    }
    if (phoneStr.length>0) {
//        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phoneStr];
//        
//        UIWebView * callWebview = [[UIWebView alloc] init];
//        
//        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
//        
//        [self.view addSubview:callWebview];
        
        [self callPhoneRequestFor:phoneStr];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSArray *    detailsArray ;
    if (companyDic) {
        
       detailsArray = [companyDic[@"uci"] componentsSeparatedByString:@"|"];
    }

    if (detailsArray.count>0) {
        
        if (indexPath.row==1) {
//            NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",detailsArray[1]];
//            
//            UIWebView * callWebview = [[UIWebView alloc] init];
//            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
//            
//            [self.view addSubview:callWebview];
            
            [self callPhoneRequestFor:detailsArray[1]];
        }
        
        if (indexPath.row==2) {

             [self callPhoneRequestFor:detailsArray[2]];
        }
    }
}

-(void)getMyCenterMessageForRequest{
    
    
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@?uphone=%@&ver=%@&uid=%@",address_url,get_company_api,USER_DEFAULTGet(@"phone"),md5ver,self.companyId];
    
    NSLog(@"parametersStr = %@",parametersStr);
    //    SHuiMBhubNoTimeLoding;
    [PostNetWorking netWorkingStr:parametersStr  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"err"] intValue]==0) {
            
            companyDic = responseObject[@"data"][0];
            companyName.frame =CGRectMake(110, 50, WIDTH -120, 20);
            companyName.text = companyDic[@"ucn"];
            companyName.numberOfLines =2;
            [companyName sizeToFit];
        } else {
            
            SHuiMBhudTextTimeStr(EorrMessageStr);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [companyImage sd_setImageWithURL:ImageUrl(companyDic[@"uca"]) placeholderImage:ImageName(@"img_home_newest")];
            
            [companyImage tapAction:^{
                
                NSArray * imageArray = @[companyDic[@"uca"]];
                XHPicView *picView = [[XHPicView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) withImgs:nil withImgUrl:imageArray];
                picView.eventBlock = ^(NSString *event){
                    NSLog(@"触发事件%@",event);
                };
                UIWindow *window = [[UIApplication sharedApplication].delegate window];
                
                [window addSubview:picView];
            }];
            
             [_tableView reloadData];
        });
        
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
    
}

-(void)lookNumberRequesr{
    
    
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,totail_lookName_api];
    NSDictionary * dic = @{@"Company":self.companyId,
                           @"UserID":USER_DEFAULTGet(@"uid"),
                           @"BrowseTime":str,
                           @"ver":md5ver,
                           @"uphone":USER_DEFAULTGet(@"phone")};
    
    [PostNetWorking postNetWorkingStr:parametersStr andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        
        if ([responseObject[@"state"] intValue]==1) {
            
        
        }
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
    
    
}

// 电话统计
-(void)callPhoneRequestFor:(NSString *)phoneStr{
    
    
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,call_phone_api];
    NSDictionary * dic = @{@"UserTel":USER_DEFAULTGet(@"phone"),
                           @"AccountTel":phoneStr,
                           @"TelTime":str, // BrowseTime
                           @"ver":md5ver};
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:parametersStr andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        
        if ([responseObject[@"state"] intValue]==1) {
            
            if (phoneStr.length>0) {
                NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phoneStr];
                
                UIWebView * callWebview = [[UIWebView alloc] init];
                
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                
                [self.view addSubview:callWebview];
            }
            
            
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
    
    
}



@end
